package loader.persister;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;

import loader.parser.adapter.SiteAdapter;

import org.dom4j.Element;

public abstract class Persister {

	private Connection conn = null;
	protected SiteAdapter adapter;

	public Persister() {
		conn = new ConnectionManager().getConnection();
	}

	public void persist(String table, HashMap<String, String> shop) {
		String sql = null;
		try {
			sql = this.createInsertStatement(table, shop);
			Statement stmt = conn.createStatement();
			stmt.execute(sql);
			stmt.close();
		} catch (SQLException e) {
			System.out.println(sql);
			e.printStackTrace();
		}
	}

	private String createInsertStatement(String table,
			HashMap<String, String> map) {

		Set<Entry<String, String>> entries = map.entrySet();
		String paras = "insert into " + table + "(";
		String values = " values(";
		for (Entry<String, String> entry : entries) {
			if (entry.getKey() == null)
				continue;
			paras += entry.getKey() + ",";
			values += "'" + entry.getValue() + "',";
		}

		paras = paras.substring(0, paras.length() - 1) + ")";
		values = values.substring(0, values.length() - 1) + ")";

		return paras + values;
	}

	public void close() throws SQLException {
		if (!this.conn.isClosed())
			this.conn.close();
	}

	protected void clear(String table) {
		try {
			String sql = "truncate table " + table;
			Statement stmt = conn.createStatement();
			stmt.execute(sql);
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void setAdapter(SiteAdapter adapter) {
		this.adapter = adapter;
	}

	public SiteAdapter getAdapter() {
		return adapter;
	}

	public abstract void clear();

	public abstract void addProperty(Element ele);

	public abstract void detectNewObject(Element ele);
}
